package com.wiiss.mock.controller;

import com.alibaba.fastjson.JSONObject;
import com.wiiss.common.annotation.Log;
import com.wiiss.common.controller.BaseController;
import com.wiiss.common.domain.AjaxResult;
import com.wiiss.common.domain.page.TableDataInfo;
import com.wiiss.common.enums.BusinessType;
import com.wiiss.common.utils.DateUtils;
import com.wiiss.common.utils.UriUtils;
import com.wiiss.common.utils.poi.ExcelUtil;
import com.wiiss.mock.domain.MockServer;
import com.wiiss.common.utils.http.HttpClientUtils;
import com.wiiss.mock.service.IMockServerService;
import com.wiiss.system.service.ISystemOrignConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.util.List;
import java.util.Random;

/**
 * 模拟服务Controller
 *
 * @author my
 * @date 2021-10-18
 */
@Api(tags = "模拟消息")
@RestController
@RequestMapping("/mcs/mock_server")
public class MockServerController extends BaseController {
    @Value("${server.port}")
    private String port ;
    @Autowired
    private IMockServerService mockServerService;

    @Autowired
    private ISystemOrignConfigService systemConfigService;

    /**
     * 查询模拟服务列表
     */
    @ApiOperation("查询模拟服务列表")
    @ApiImplicitParam(name = "list" , value = "查询模拟服务列表" , dataType = "MockServer")
    @PreAuthorize("@ss.hasPermi('mcs:mock_server:list')")
    @GetMapping("/list")
        public TableDataInfo list(MockServer mockServer) {
        startPage();
        List<MockServer> list = mockServerService.selectMockServerList(mockServer);
        return getDataTable(list);
    }

    /**
     * 导出模拟服务列表
     */
    @ApiOperation("导出模拟服务列表")
    @ApiImplicitParam(name = "export" , value = "导出模拟服务列表" , dataType = "MockServer")
    @PreAuthorize("@ss.hasPermi('mcs:mock_server:export')")
    @Log(title = "模拟服务" , businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MockServer mockServer) {
        List<MockServer> list = mockServerService.selectMockServerList(mockServer);
        ExcelUtil<MockServer> util = new ExcelUtil<MockServer>(MockServer. class);
        return util.exportExcel(list, "mock_server");
    }

    /**
     * 获取模拟服务详细信息
     */
    @ApiOperation("获取模拟服务详细信息")
    @ApiImplicitParam(name = "getInfo" , value = "获取模拟服务详细信息" , dataType = "MockServer")
    @PreAuthorize("@ss.hasPermi('mcs:mock_server:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(mockServerService.selectMockServerById(id));
    }

    /**
     * 新增模拟服务
     */
    @ApiOperation("新增模拟服务")
    @ApiImplicitParam(name = "add" , value = "新增模拟服务" , dataType = "MockServer")
    @PreAuthorize("@ss.hasPermi('mcs:mock_server:add')")
    @Log(title = "模拟服务" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MockServer mockServer) {
        return toAjax(mockServerService.insertMockServer(mockServer));
    }

    /**
     * 修改模拟服务
     */
    @ApiOperation("修改模拟服务")
    @ApiImplicitParam(name = "edit" , value = "修改模拟服务" , dataType = "MockServer")
    @PreAuthorize("@ss.hasPermi('mcs:mock_server:edit')")
    @Log(title = "模拟服务" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MockServer mockServer) {
        return toAjax(mockServerService.updateMockServer(mockServer));
    }

    /**
     * 删除模拟服务
     */
    @ApiOperation("删除模拟服务")
    @ApiImplicitParam(name = "remove" , value = "删除模拟服务" , dataType = "MockServer")
    @PreAuthorize("@ss.hasPermi('mcs:mock_server:remove')")
    @Log(title = "模拟服务" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(mockServerService.deleteMockServerByIds(ids));
    }

    /**
     * 虚拟消息
     */
    @ApiOperation("虚拟PUSH消息")
    @ApiImplicitParam(name = "pushMsg" , value = "虚拟消息" , dataType = "String")
    @PostMapping(value = "/push/{type}/{msg}/{processInstanceId}")
    public AjaxResult pushMsg(@PathVariable("type") String type,@PathVariable("msg") String msg,@PathVariable("processInstanceId") String processInstanceId) {
        try {
            String reqJson = "";
            String respJson = "";
            if("RCS-HK".equals(type)){
                reqJson = "{\n" +
                        "\t\"code\": 0,\n" +
                        "\t\"msg\": \"\",\n" +
                        "\t\"data\": \"data\",\n" +
                        "\t\"method\": \"method\",\n" +
                        "\t\"mapDataCode\": \"mapDataCode\",\n" +
                        "\t\"reqCode\": \"reqCode\",\n" +
                        "\t\"taskCode\": \"taskCode\",\n" +
                        "\t\"cooY\": \"Y坐标\",\n" +
                        "\t\"cooX\": \"cooX\",\n" +
                        "\t\"robotCode\": \"robotCode\",\n" +
                        "\t\"currentPositionCode\": \"currentPositionCode\",\n" +
                        "\t\"mapCode\": \"mapCode\"\n" +
                        "}";
                JSONObject obj = JSONObject.parseObject(reqJson);
                obj.put("method", msg);
                obj.put("taskCode", processInstanceId);
                reqJson = JSONObject.toJSONString(obj);
                URI uri = UriUtils.getUri(systemConfigService.getUrl("rcs-hk", "rcs-hk"));
                respJson = HttpClientUtils.sendPostByJson(uri.toString()+"/mcs/v1/agvCallback", reqJson, 3);
            }else if("RCS-XJ".equals(type)) {

                HttpGet httpGet = new HttpGet("http://localhost:9999/mcs/v1/" + processInstanceId);
                CloseableHttpResponse response = HttpClients.createDefault().execute(httpGet);
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                JSONObject jsonObject = JSONObject.parseObject(content);
                JSONObject data = jsonObject.getJSONObject("data");

                JSONObject obj = new JSONObject();
                obj.put("method", msg);
                obj.put("taskCode", data.getString("acsTaskCode"));
                obj.put("robotCode", "123");

                reqJson = JSONObject.toJSONString(obj);
                URI uri = UriUtils.getUri(systemConfigService.getUrl("rcs-hk", "rcs-hk"));
                respJson = HttpClientUtils.sendPostByJson(uri.toString() + "/mcs/v1/agvCallback", reqJson, 3);
            }else if("WIP".equals(type)){
                reqJson = "{\n" +
                        "\t\"taskCode\": \"203434343403434\",\n" +
                        "\t\"data\": \"\",\n" +
                        "\t\"method\": \"wipAllowIn\"\n" +
                        "}";
                JSONObject obj = JSONObject.parseObject(reqJson);
                obj.put("method", msg);
                obj.put("taskCode", processInstanceId);
                obj.put("reqTime", DateUtils.getNowDate());
                reqJson = JSONObject.toJSONString(obj);
                URI uri = UriUtils.getUri(systemConfigService.getUrl("wip", "wip"));
                respJson = HttpClientUtils.sendPostByJson(uri.toString()+"/mcs/v1/wipCallback", reqJson, 3);
            }else if("WCS".equals(type)){
                reqJson = "{\n" +
                        "\t\"taskCode\": \"12345678\",\n" +
                        "\t\"repCode\": \"12345678\",\n" +
                        "\t\"robotCode\": \"agv1\",\n" +
                        "\t\"currentPositionCode\": \"100\"\n" +
                        "}";
                JSONObject obj = JSONObject.parseObject(reqJson);
                obj.put("taskCode", processInstanceId);
                obj.put("repCode", msg);
                obj.put("currentPositionCode", new Random().nextInt(1000));
                reqJson = JSONObject.toJSONString(obj);
                URI uri = UriUtils.getUri(systemConfigService.getUrl("wcs", "wcs"));
                respJson = HttpClientUtils.sendPostByJson(uri.toString()+"/mcs/v1/wcsCallback", reqJson, 0);
            }else if("LINE".equals(type)) {

                HttpGet httpGet = new HttpGet("http://localhost:"+port+"/mcs/v1/" + processInstanceId);
                CloseableHttpResponse response = HttpClients.createDefault().execute(httpGet);

                JSONObject obj = new JSONObject();
                obj.put("method", msg);
                obj.put("taskCode", processInstanceId);
                obj.put("data", "");

                reqJson = JSONObject.toJSONString(obj);
                URI uri = UriUtils.getUri(systemConfigService.getUrl("line", "line"));
                respJson = HttpClientUtils.sendPostByJson(uri.toString() + "/mcs/v1/lineCallback", reqJson, 3);
            }else if("LCS".equals(type)) {

                reqJson = "{\n" +
                        "\t\"taskCode\": \"203434343403434\",\n" +
                        "\t\"data\": \"\",\n" +
                        "\t\"method\": \"wipAllowIn\"\n" +
                        "}";
                JSONObject obj = JSONObject.parseObject(reqJson);
                obj.put("method", msg);
                obj.put("taskCode", processInstanceId);
                obj.put("data", "");

                reqJson = JSONObject.toJSONString(obj);
                URI uri = UriUtils.getUri(systemConfigService.getUrl("lcs", "lcs"));
                respJson = HttpClientUtils.sendPostByJson(uri.toString() + "/mcs/v1/liftCallback", reqJson, 3);
            }
            return AjaxResult.success(JSONObject.parseObject(respJson));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
